package com.campusexpresspickup.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campusexpresspickup.entity.UserMenu;
import com.campusexpresspickup.mapper.UserMenuMapper;
import com.campusexpresspickup.service.IUserMenuService;
import com.campusexpresspickup.dto.UserMenuNode;
import com.campusexpresspickup.page.UserMenuPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 后台菜单表 服务实现类
 * </p>
 *
 * @author lq
 * @since 2021-11-17
 */
@Service
public class UserMenuServiceImpl extends ServiceImpl<UserMenuMapper, UserMenu> implements
    IUserMenuService {

  private final UserMenuMapper userMenuMapper;

  public UserMenuServiceImpl(UserMenuMapper userMenuMapper) {
    this.userMenuMapper = userMenuMapper;
  }

  @Override
  public List<UserMenu> getUserResourceList(UserMenuPage userMenuPage) {
    return userMenuMapper.findMenuList(userMenuPage);
  }

  @Override
  public List<UserMenuNode> treeList() {
    List<UserMenu> userMenuList = userMenuMapper.selectList(new QueryWrapper<>());
    return userMenuList.stream().filter(menu -> menu.getParentId().equals(0L))
        .map(menu -> covertMenuNode(menu, userMenuList)).collect(Collectors.toList());
  }

  private UserMenuNode covertMenuNode(UserMenu menu, List<UserMenu> menuList) {
    UserMenuNode node = new UserMenuNode();
    BeanUtils.copyProperties(menu, node);
    List<UserMenuNode> children = menuList.stream()
        .filter(subMenu -> subMenu.getParentId().equals(menu.getId()))
        .map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
    node.setChildren(children);
    return node;
  }
}
